package com.haiertvbic.tvwa;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.haiertvbic.tvnow.R;
import com.haiertvbic.tvnow.model.ChannelBean;
import com.haiertvbic.tvnow.model.ChannelPagekageBean;
import com.haiertvbic.tvnow.model.SingleHandler;
import com.haiertvbic.tvnow.protocol.CAEProtocol;
import com.haiertvbic.tvnow.service.ServiceUtil;
import com.haiertvbic.tvnow.service.SwitchChanellCallback;
import com.haiertvbic.tvnow.util.AppManager;
import com.haiertvbic.tvnow.util.Constant;
import com.haiertvbic.tvnow.util.LocateToast;
import com.haiertvbic.tvnow.util.ProduceThread;
import com.haiertvbic.tvnow.util.SLog;
import com.haiertvbic.tvnow.util.SetActivityView;

public class TVWAMainActivity extends Activity {
	// 没有获取频道数据
	private static final int GET_FAVCHAS_FAIL = 100000;
	// 获取频道数据成功
	private static final int GET_FAVCHAS_SUC = 100002;
	// 数据库错误
	private static final int DB_ERROR = 100003;
	// 未知错误
	private static final int NOT_SURE_ERROR = 100004;
	protected static final String TAG = "FavChannel";
	private Activity context = TVWAMainActivity.this;

	// 显示加载进度
	private ProgressBar cha_bar;
	// 显示排名的频道
	private ListView chaListView;
	// 显示操作时间提示
	public static TextView showTime_1;
	public static View fView;

	// 从CAE获取的返回的数据包

	private ChannelPagekageBean favChaPkg;
	private int which;
	private boolean canToNext;
	private boolean canSwitch;
	private String action = "com.haiertvbic.tvwa.TVWA_LAUNCH";// 窗口被按键调出后给VD发广播，开机三分钟后不要再调出窗口
	private int currentCha = -200;
	private int switchCha = -200;
	// 从CAE获取我喜爱的频道
	private ArrayList<ChannelBean> mChannels;
	private Handler myHandler;

	/**
	 * 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.acitivity_main_tvwa);
		initView();
		// 设置窗体的样式
		fView = SetActivityView.setActivityViewTvwa(getWindow(),
				getWindowManager());
		Intent brodcastIntent = new Intent();
		brodcastIntent.setAction(action);
		// 发送窗口启动的广播，开机三分钟后不再调出
		sendBroadcast(brodcastIntent);

		SingleHandler sHandler = SingleHandler.returnHandler();
		sHandler.setTextView(showTime_1);
		ProduceThread.produceThread(sHandler);
		AppManager.activityList.add(this);

		myHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				switch (msg.what) {
				case GET_FAVCHAS_FAIL:
					// 获取频道数据失败，消失加载数据进度条
					cha_bar.setVisibility(View.GONE);
					Toast.makeText(
							context,
							getResources().getString(
									R.string.get_chann_data_failed),
							Toast.LENGTH_SHORT).show();
					break;
				case GET_FAVCHAS_SUC:
					// 获取数据成功，适配显示数据，消失加载数据的进度条
					cha_bar.setVisibility(View.GONE);
					MyFavChasAdapter	adapter = new MyFavChasAdapter(context, mChannels);
					chaListView.setAdapter(adapter);
					canToNext = true;
					canSwitch = true;
					break;
				case DB_ERROR:
					// 数据库错误
					cha_bar.setVisibility(View.GONE);
					Toast.makeText(context,
							getResources().getString(R.string.db_error),
							Toast.LENGTH_SHORT).show();
					break;
				case NOT_SURE_ERROR:
					// 不确定的错误
					cha_bar.setVisibility(View.GONE);
					Toast.makeText(
							context,
							getResources().getString(
									R.string.Indeterminate_error),
							Toast.LENGTH_SHORT).show();
					break;

				case 0:
					LocateToast.locateToast(
							context,
							200,
							getResources().getString(
									R.string.read_change_msg_failed));
					break;

				case 4004500:
					LocateToast.locateToast(context, 200,
							getResources().getString(R.string.change_success));
					currentCha = switchCha;
					break;

				case 4004501:
					LocateToast.locateToast(
							context,
							200,
							getResources().getString(
									R.string.channel_non_existent));
					break;

				case 4004502:
					LocateToast.locateToast(
							context,
							200,
							getResources().getString(
									R.string.please_connect_crb));
					break;

				case 4004503:
					LocateToast.locateToast(context, 200,
							getResources().getString(R.string.no_set_crb));
					break;

				case -2002:
					LocateToast.locateToast(context, 200,
							getResources()
									.getString(R.string.connect_break_off));
					break;

				default:
					break;
				}
			}
		};

		// 从CAE获取喜爱的频道数据
		getFavChaFromCae();
	}

	private void getFavChaFromCae() {
		cha_bar.setVisibility(View.VISIBLE);
		Thread getFavChasThread = new Thread() {

			@Override
			public void run() {
//				ChannelPagekageBean favChaPkg = null;
//				mChannels = new ArrayList<ChannelBean>();
//				int[] cid = { 46, 44, 43, 5, 6 };
//				String[] cidName = { "湖南卫视", "江苏卫视", "浙江卫视", "CCTV-4中文国际",
//						"CCTV-5" };
//				for (int i = 0; i < cid.length; i++) {
//					ChannelBean fav = new ChannelBean();
//					fav.setChannel_id(cid[i]);
//					fav.setChannel_name(cidName[i]);
//					mChannels.add(fav);
//				}
//				if (mChannels != null) {
//					myHandler.sendEmptyMessage(GET_FAVCHAS_SUC);
//				}
				super.run();
				favChaPkg = CAEProtocol.getFavChannel(1,
						Constant.CHANNEL_NUMBER);

				if (favChaPkg == null) {
					// 获取数据失败
					myHandler.sendEmptyMessage(GET_FAVCHAS_FAIL);
				} else if (favChaPkg.getReturn_code() == 4006002
						|| favChaPkg.getReturn_code() == 4006003) {
					// 操作数据库失败
					myHandler.sendEmptyMessage(DB_ERROR);
				} else if (favChaPkg.getReturn_code() == 4006000
						|| favChaPkg.getReturn_code() == 4006001) {
					// 获取数据成功
					mChannels = favChaPkg.getChannels();
					if (mChannels!=null) {
						myHandler.sendEmptyMessage(GET_FAVCHAS_SUC);
					}
				} else if (favChaPkg.getReturn_code() == 4006004) {
					// 发生未知错误
					myHandler.sendEmptyMessage(NOT_SURE_ERROR);
				}

			}

		};
		getFavChasThread.start();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		chaListView = (ListView) findViewById(R.id.cha_list);
		showTime_1 = (TextView) findViewById(R.id.show_time_1);
		cha_bar = (ProgressBar) findViewById(R.id.cha_bar);
		chaListView.setOnItemSelectedListener(new OnItemSelectedListener() {
			boolean first = false;

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				which = arg2;
				if (first) {
					ProduceThread.seconds = Constant.SECOND_TIME;
				}
				first = true;
			}

			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		chaListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				int chaId=  mChannels.get(arg2).getChannel_id();
				SLog.d(TAG, "cha_id == " + chaId);
				if (canSwitch&& currentCha != chaId) {
					ServiceUtil.changeChannel(context, chaId,
							new SwitchChanellCallback() {

								@Override
								public void returnData(int source,
										int resultCode, int result) {
									myHandler.sendEmptyMessage(resultCode);
								}
							});
					switchCha = chaId;
				}
				ProduceThread.seconds = Constant.SECOND_TIME;
			}
		});
	}

	/**
	 * 处理右按键事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		ProduceThread.seconds = Constant.SECOND_TIME;
		SLog.d(TAG, "在第一个界面你所按的键值是=====" + keyCode);
		if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
			if (canToNext) {
				Intent intent = new Intent();
				intent.putExtra("CHA_NAME", mChannels.get(which)
						.getChannel_name());
				intent.putExtra("CHA_ID", mChannels.get(which)
						.getChannel_id());
				intent.setClass(this, TVWAProgramListActivity.class);
				startActivity(intent);
				SLog.v("lfav", "跳转第二个界面");
				fView.setVisibility(View.INVISIBLE);
			}
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			ProduceThread.canRun = false;
			// progressDialog = null;
		} else if (keyCode == KeyEvent.KEYCODE_1) {
			int chaId = mChannels.get(0).getChannel_id();
			if (canSwitch && (currentCha != chaId)) {
				ServiceUtil.changeChannel(context, chaId,
						new SwitchChanellCallback() {

							@Override
							public void returnData(int source, int resultCode,
									int result) {

							}
						});
				switchCha =chaId;
			}
		} else if (keyCode == KeyEvent.KEYCODE_2) {
			int chaId = mChannels.get(1).getChannel_id();
			if (canSwitch && (currentCha != chaId)) {
				ServiceUtil.changeChannel(context,chaId,
						new SwitchChanellCallback() {

							@Override
							public void returnData(int source, int resultCode,
									int result) {

							}
						});
				switchCha = chaId;
			}
		} else if (keyCode == KeyEvent.KEYCODE_3) {
			int chaId = mChannels.get(2).getChannel_id();
			if (canSwitch && (currentCha != chaId)) {
				ServiceUtil.changeChannel(context, chaId,
						new SwitchChanellCallback() {

							@Override
							public void returnData(int source, int resultCode,
									int result) {

							}
						});
				switchCha = chaId;
			}
		} else if (keyCode == KeyEvent.KEYCODE_4) {
			int chaId = mChannels.get(3).getChannel_id();
			if (canSwitch && (currentCha != chaId)) {
				ServiceUtil.changeChannel(context, chaId,
						new SwitchChanellCallback() {

							@Override
							public void returnData(int source, int resultCode,
									int result) {

							}
						});
				switchCha = chaId;
			}

		} else if (keyCode == KeyEvent.KEYCODE_5) {
			int chaId = mChannels.get(4).getChannel_id();
			if (canSwitch && (currentCha != chaId)) {
				ServiceUtil.changeChannel(context, chaId,
						new SwitchChanellCallback() {

							@Override
							public void returnData(int source, int resultCode,
									int result) {
								// TODO Auto-generated method stub

							}
						});
				switchCha = chaId;
			}

		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
				| keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			ProduceThread.seconds = 60;

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// progressDialog = null;
	}

	class MyFavChasAdapter extends BaseAdapter {
		private Context context;
		private ArrayList<ChannelBean> favChannels;
		private LayoutInflater inflater;

		public MyFavChasAdapter(Context context,
				ArrayList<ChannelBean> favChannels) {
			this.context = context;
			this.favChannels = favChannels;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return favChannels.size();
		}

		@Override
		public Object getItem(int position) {
			return favChannels.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.layout_channel_tvwa_item, null);
			}
			TextView chaIndex = (TextView) convertView
					.findViewById(R.id.channel_id);
			TextView chaName = (TextView) convertView
					.findViewById(R.id.channel_name);
			chaIndex.setText("" + (position + 1));
			chaName.setText(favChannels.get(position).getChannel_name());
			return convertView;
		}
	}
}